﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;

namespace Sample.RegularExpression
{
    class RegexSample
    {
        public static void Execute()
        {
            StringBuilder output = new StringBuilder();

            string pattern = null;
            string input = null;

            /*pattern = "((A(b)))";
            input = "XYZAbcAbcAbcXYZAbcAb";*/

            //input = ReadInput();
            input = "1851 1999 1950 1905 2003";
            pattern = "(?!19)\\d+\\b";

            output.AppendLine(input);

            string prefix = "";
            Regex r = new Regex(pattern);
            MatchCollection matches = r.Matches(input);
            output.AppendLine(String.Format("Number of matches found = {0}", matches.Count.ToString()));
            foreach(Match aMatch in matches)
            {
                prefix = "\t";
                output.Append(prefix);
                output.AppendLine(String.Format("Value of match: \"{0}\", Index of match: {1}", aMatch.Value, aMatch.Index));
                GroupCollection groups = aMatch.Groups;
                output.Append(prefix);
                output.AppendLine(String.Format("Number of groups found = {0}", groups.Count));
                foreach (Group aGroup in groups)
                {
                    prefix = "\t\t";
                    output.Append(prefix);
                    output.AppendLine(String.Format("Value of group: \"{0}\", Index of group: {1}", aGroup.Value, aGroup.Index));
                    CaptureCollection captures = aGroup.Captures;
                    output.Append(prefix);
                    output.AppendLine(String.Format("Number of captures found = {0}", captures.Count));
                    foreach (Capture aCapture in captures)
                    {
                        prefix = "\t\t\t";
                        output.Append(prefix);
                        output.AppendLine(String.Format("Value of capture: \"{0}\", Index of capture: {1}", aCapture.Value, aCapture.Index));
                    }
                }
            }

            //WriteOutput(output.ToString());
            Console.WriteLine(output.ToString());
        }

        private static string ReadInput()
        {
            StreamReader reader = new StreamReader(new FileStream(@"E:\Temporary\URL.txt", FileMode.Open, FileAccess.Read));
            string input = reader.ReadLine();
            reader.Close();

            return input;
        }

        private static void WriteOutput(string output)
        {
            StreamWriter writer = new StreamWriter(new FileStream(@"E:\Temporary\result.txt", FileMode.Create, FileAccess.Write));
            writer.Write(output);
            writer.Flush();
            writer.Close();
        }
    }
}
